import axiosInstance from './axiosInstance';

// 订单商品接口
export interface OrderItem {
  id: number;
  orderId: number;
  productId: number;
  productName: string;
  productImage: string;
  quantity: number;
  price: number;
}

// 订单接口
export interface Order {
  id: number;
  userId: number;
  totalAmount: number;
  status: 'pending' | 'paid' | 'shipped' | 'delivered' | 'cancelled';
  shippingAddress: any;
  billingAddress: any;
  paymentMethod: string;
  createdAt: string;
  updatedAt: string;
  orderItems: OrderItem[];
}

// 地址接口 - 与后端验证规则匹配
export interface Address {
  firstName: string;
  lastName: string;
  phone: string;
  address: string;  // 后端验证规则中使用的是 address 而不是 addressLine1
  addressLine2?: string;
  city: string;
  postalCode: string;  // 后端验证规则中使用的是 postalCode 而不是 zipCode
  state?: string;      // state 是可选的
  country: string;
}

// 获取订单列表参数接口
interface GetOrdersParams {
  page?: number;
  limit?: number;
  status?: string;
  startDate?: string;
  endDate?: string;
}

// 在 orderService 对象中添加 createOrder 方法
export const orderService = {
  // 获取用户订单列表
  getUserOrders: async (params?: GetOrdersParams) => {
    return axiosInstance.get('/orders/user', { params });
  },

  // 获取单个订单详情
  getOrder: async (id: number) => {
    return axiosInstance.get(`/orders/${id}`);
  },

  // 创建订单
  // 注意：商品项（items）由后端从用户购物车自动填充，前端无需传递
  createOrder: async (orderData: {
    shippingAddress: Address;
    billingAddress: Address;
    paymentMethod: string;
    notes?: string;
  }) => {
    try {
      // 确保所有必需字段都存在并符合后端验证规则
      const data = {
        shippingAddress: orderData.shippingAddress,
        billingAddress: orderData.billingAddress,
        paymentMethod: orderData.paymentMethod || 'credit_card',
        notes: orderData.notes || ''
      };
      
      console.log('Sending order data:', JSON.stringify(data, null, 2));
      const response = await axiosInstance.post('/orders', data);
      return response;
    } catch (error: any) {
      console.error('Order creation failed:', error.response?.data || error);
      throw error;
    }
  },

  // 取消订单
  cancelOrder: async (id: number) => {
    return axiosInstance.patch(`/orders/${id}/cancel`);
  },

  // 支付订单
  processPayment: async (id: number) => {
    return axiosInstance.post(`/orders/${id}/payment`);
  }
};